#ifndef STRUTIL_COMSTATIC_H_H_
#define STRUTIL_COMSTATIC_H_H_
#include <list>
#include <string>
#include "mstring.h"

std::wstring __stdcall FormatW(const wchar_t *format, ...);
std::string __stdcall FormatA(const char *fmt, ...);

std::string __stdcall AtoU(const std::string &);
std::string __stdcall UtoA(const std::string &);
std::wstring __stdcall AtoW(const std::string &);
std::string _stdcall WtoA(const std::wstring &);
std::wstring __stdcall UtoW(const std::string &);
std::string __stdcall WtoU(const std::wstring &);

std::list<std::mstring> SplitStrA(const std::mstring &str, const std::mstring &split);
std::list<std::ustring> SplitStrW(const std::ustring &str, const std::ustring &split);

std::string StringTrimLeftA(const std::string &str);
std::string StringTrimRightA(const std::string &str);
std::string StringTrimA(const std::string &str);

std::wstring StringTrimLeftW(const std::wstring &wstr);
std::wstring StringTrimRightW(const std::wstring &wstr);
std::wstring StringTrimW(const std::wstring &wstr);

template <typename Ch>
size_t StringRefindSubStr(
    const std::basic_string<Ch> &strBuffer,
    const std::basic_string<Ch> &strSubStr,
    size_t nPos = -1,
    size_t nRange = -1,
    bool bCaseSensitive = false
    ) {
    if (strBuffer.empty() || strSubStr.empty() || strSubStr.size() > strBuffer.size()) {
        return -1;
    }

    if (-1 == nPos) {
        nPos = strBuffer.size() - 1;
    }

    if (nPos >= strBuffer.size()) {
        nPos = strBuffer.size() - 1;
    }

    if (nPos < strSubStr.size() - 1) {
        return -1;
    }
    nPos -= (strSubStr.size() - 1);
    if (nPos < nRange) {
        nRange = nPos + 1;
    }

    size_t nCount = 0;
    size_t i = 0, j = 0;
    for (i = nPos; nCount != nRange; i--, nCount++) {
        for (j = 0; j != strSubStr.size(); j++) {
            Ch ch1, ch2;
            ch1 = strBuffer.at(i + j), ch2 = strSubStr.at(j);
            if (!bCaseSensitive) {
                if (ch1 >= 'A' && ch1 <= 'Z') {
                    ch1 |= 32;
                }

                if (ch2 >= 'A' && ch2 <= 'Z') {
                    ch2 |= 32;
                }
            }

            if (ch1 != ch2) {
                break;
            }
        }

        if (j == strSubStr.size()) {
            return i;
        }
    }
    return -1;
}
#endif //STRUTIL_COMSTATIC_H_H_